//
//  IcMaterialsListViewController.m
//  IceClear
//
//  Created by P & C on 11-03-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "IcMaterialsListViewController.h"
#import "IcMaterialDetailViewController.h"


@implementation IcMaterialsListViewController


@synthesize materials;
@synthesize appModelsManager;


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	
	searchBar = [[UISearchBar alloc] initWithFrame:self.tableView.bounds];
    [searchBar sizeToFit];
    searchBar.delegate = self;
    
    self.tableView.tableHeaderView = searchBar;
    mutableMaterials = [self.materials mutableCopy];
	
	self.view.backgroundColor = [UIColor clearColor];
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    int c = [mutableMaterials count];
	return c > 0 ? c : 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableMaterials count] > 0 ? [[mutableMaterials objectAtIndex:section] count] : 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	if ([mutableMaterials count] > 0) {
		IcMaterial* material = (IcMaterial *)[[mutableMaterials objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
		
		// Configure the cell...
		NSString* text = material.title;
		
		cell.textLabel.text = text;
		cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
		cell.detailTextLabel.text = material.details;
		cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
		cell.detailTextLabel.textColor = [UIColor brownColor];
	}
	else {
		cell.textLabel.text = @"No Materials Found!";
		cell.detailTextLabel.text = @"";
	}

	
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString* t = @"";
	
	if ([mutableMaterials count] > 0 ) {
		switch (section) {
			case 0:
				t = @"Dry Chemicals";
				break;
			case 1:
				t = @"Liquid Chemicals";
				break;
			case 2:
				t = @"Dry Chemical Blends";
				break;
				
			default:
				break;
		}
	}
	
	return t;
}


/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [(IcMaterial *)[self.materials objectAtIndex:section] title];
}
*/


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	
    // Navigation logic may go here. Create and push another view controller.
	// show details of the selected material
    IcMaterialDetailViewController *detailViewController = [[IcMaterialDetailViewController alloc] 
															initWithStyle:UITableViewStyleGrouped];
	IcMaterial* material = (IcMaterial *)[[mutableMaterials objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	
    detailViewController.appModelsManager = self.appModelsManager;
	detailViewController.title = material.title;
	detailViewController.material = material;
	
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}


#pragma mark -
#pragma mark Search

- (void)searchBarTextDidBeginEditing:(UISearchBar *)aSearchBar {
	// only show the status bar’s cancel button while in edit mode
	aSearchBar.showsCancelButton = YES;
	aSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar {
	aSearchBar.showsCancelButton = NO;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
    // Stop editing and hide the keyboard
    [aSearchBar endEditing:YES];
    
    // Re-filter the array of names
    [mutableMaterials removeAllObjects];
    NSString* query = aSearchBar.text;
	
	if (query.length == 0) {
		// Only search if we have a non-zero length query string
		[mutableMaterials addObjectsFromArray:self.materials];
	}
	else {
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
		NSMutableArray* tmp = [NSMutableArray array];
		
		for (NSArray * a in self.materials) {
			for (IcMaterial * m in a) {
				// search title and details
				NSRange r1 = [m.title rangeOfString:query options:NSCaseInsensitiveSearch];
				NSRange r2 = [m.details rangeOfString:query options:NSCaseInsensitiveSearch];
				
				if (r1.length > 0) {
					[tmp addObject:m];
				}
				else if (r2.length  > 0) {
					[tmp addObject:m];
				}
			}
			
			if ([tmp count] > 0) {
				[mutableMaterials addObject:[tmp mutableCopy]];
				[tmp removeAllObjects];
			}
		}
		
		[pool release];
	}
    
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar {
	// if a valid search was entered but the user wanted to cancel, bring back the main list content
	[mutableMaterials removeAllObjects];
	[mutableMaterials addObjectsFromArray:self.materials];
	
	@try{
		[self.tableView reloadData];
	}
	@catch(NSException *e){
		NSLog(@"Caught exception while handling search cancel %@", e);
	}
	
	[searchBar resignFirstResponder];
	
	searchBar.text = @"";	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[materials release];
	[mutableMaterials release];
	[appModelsManager release];
	[searchBar release];
    [super dealloc];
}


@end

